package lol.clann.minecraft.springboot.plugin.hook;

import lol.clann.minecraft.springboot.api.context.PluginContext;
import lol.clann.minecraft.springboot.api.model.core.Plugin;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

/**
 * 把插件的bean缓存到plugin里
 * 这个需要最先触发,这样其他地方才能通过bean找到plugin
 * @author pyz
 * @date 2019/5/2 4:59 PM
 */
@Order(Integer.MIN_VALUE)
@Component
public class PluginBeanDetector implements InstantiationAwareBeanPostProcessor {

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if (!bean.getClass().getName().startsWith("org.springframework.")) {
            Class clazz = ClassUtils.getUserClass(bean);
            Plugin plugin = PluginContext.getPluginByClass(clazz);
            if (plugin != null) {
                plugin.getBeans().add(bean);
            }
        }
        return true;
    }
}
